package com.fanyouzhao.ehome2.admin.controller;


import com.fanyouzhao.ehome2.admin.annotation.NeedsLogin;
import com.fanyouzhao.ehome2.admin.exception.BusinessException;
import com.fanyouzhao.ehome2.admin.service.AdminService;
import com.fanyouzhao.ehome2.core.pojo.Admin;
import com.fanyouzhao.ehome2.core.util.JsonResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author: fanyouzhao
 * @date: 11:01 2021/6/23
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    AdminService adminService;

    JsonResult jsonResult = null;

    @PostMapping("/login")
    public JsonResult login(Admin admin, HttpSession session) throws BusinessException, IllegalAccessException {
        Admin login = adminService.login(admin);
        if (login!=null){
            session.setAttribute("phone",admin.getPhone());
            System.out.println("登录成功");
            jsonResult = new JsonResult("1","登录成功",login);
        }else {
            throw new BusinessException("登录失败，账号或密码错误！");
        }
        return jsonResult;
    }

    @GetMapping("/logout")
    public JsonResult logout(HttpSession session) throws BusinessException {
        session.removeAttribute("phone");
        jsonResult = new JsonResult("1","退出登录成功");
        return jsonResult;
    }

    @NeedsLogin
    @PostMapping("selectById")
    public JsonResult selectById(@RequestParam("id") Integer id) throws BusinessException {
        Admin admin = adminService.selectById(id);
        if (admin!=null){
            jsonResult = new JsonResult("1","查询成功",admin);
        }else {
            throw new BusinessException("查询失败");
        }
        return jsonResult;
    }
}
